use std::fs;
use std::path::PathBuf;

use crate::{list_directory, program_root};

pub fn excel_copy() {
	let start_time = chrono::Local::now(); //获取结束时间
	let (dirs, root_dir) = list_directory::get_directory();
	//  搜索excel
	excel_sort(dirs, &root_dir);

	let end_time = chrono::Local::now(); //获取结束时间
	let duration_time = end_time.signed_duration_since(start_time).to_std().unwrap(); //耗时
	println!(
		"提取任务开始时间 : {:?},结束时间 :{:?},耗时:{:?}",
		start_time.format("%Y-%m-%d %H:%M:%S").to_string(),
		end_time.format("%Y-%m-%d %H:%M:%S").to_string(),
		duration_time
	);
	// 返回主菜单
	program_root();
}

fn excel_sort(dirs: fs::ReadDir, root_dir: &str) {
	let extensions: Vec<&str> = vec!["xlsx", "xls"];
	for entry in dirs {
		let entry = entry.expect("读取文件夹失败");
		let path = entry.path();
		if path.is_dir() {
			println!("正在遍历处理文件夹: {}", path.display());
			excel_sort(fs::read_dir(path).unwrap(), root_dir); //递归遍历文件夹
		} else {
			let ext = match path.extension() {
				Some(ext) => ext.to_str().unwrap(),
				None => "",
			};
			if extensions.contains(&ext) {
				//根据图片后缀名 在扩展名列表中查找 有才处理
				copy_excel(path, root_dir);
			}
		}
	}
}

fn copy_excel(src: PathBuf, root_dir: &str) {
	let f_name = src.to_str().unwrap().to_string();
	println!("正在处理文件: {}", f_name);
	let root_dir_name = "export\\";
	let parent_path = src.parent().unwrap().to_str().unwrap();
	//  根据输入的root——dir的长度来生成文件保存目录
	let dist_path = match root_dir.len() {
		0 => root_dir.to_owned() + root_dir_name + parent_path,
		_ => {
			let p_path: Vec<&str> = parent_path.split(root_dir).collect();
			let d_r_dir = format!("{}\\{}\\{}", root_dir, root_dir_name, p_path[1]);
			d_r_dir
		}
	};
	println!(
		"上级文件夹：{}",
		src.parent().unwrap().to_str().unwrap().to_string()
	);
	let dist_path_dir = PathBuf::from(dist_path);
	//  目录不存在就创建目录
	if !dist_path_dir.exists() {
		fs::create_dir_all(&dist_path_dir).expect("创建目录失败");
	}
	//  同文件名称拼接完成保存路径
	let dist_path_end = dist_path_dir.join(src.file_name().unwrap());
	// 复制文件
	fs::copy(src, dist_path_end).expect("复制文件失败");
}
